package xu.zhi.qing.visitor.controller;

import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import xu.zhi.qing.common.constant.Configuration;
import xu.zhi.qing.common.entity.ResponseJson;
import xu.zhi.qing.share.dto.ShareConditionDto;
import xu.zhi.qing.share.entity.ShareCondition;
import xu.zhi.qing.share.service.ShareService;
import xu.zhi.qing.share.vo.SharePageVo;
import xu.zhi.qing.user.service.UserService;

import javax.servlet.http.HttpServletRequest;

@Controller
@Scope("prototype")
@RequestMapping("/visitor")
public class VisitorController {
	
	@Autowired
	ShareService shareService;
	
	@Autowired
	UserService userService;
	
	@RequestMapping("/indexUI")
	public ModelAndView indexUI(){
		return new ModelAndView("visitor/index");
	}
	
	@RequestMapping("/rankingPage")
	public ModelAndView rankingPage(){
		return new ModelAndView("visitor/ranking");
	}
	
	@RequestMapping("/searchPage")
	public ModelAndView searchPage(){
		return new ModelAndView("visitor/search");
	}

	
	/**
     * 显示分页分享列表
     * @param request 请求
     * @return
     */
    @ResponseBody
    @RequestMapping("/listShare")
    public SharePageVo listShare(ShareConditionDto dto, HttpServletRequest request) {
        //参数验证
        if (dto.getPageNo() == null) {
            //默认显示第一页
            dto.setPageNo(1);
        }
        if (dto.getPageSize() == null) {
            //默认页大小
            dto.setPageSize(Configuration.SHARE_PAGE_SIZE);
        }
        ShareCondition shareCondition = new ShareCondition();
		shareCondition = dto.copyDto(shareCondition);
        //封装要传递的参数
        shareCondition.setCurrentUserId(null);

        Integer shareType = shareCondition.getShareType();
		SharePageVo respone = null;
        if (shareType == null || shareType.equals(Configuration.SHARE_TYPE_DEFAULT)) {
            //默认的分享
			respone = shareService.findByPage(shareCondition);
        }else if (shareType.equals(Configuration.SHARE_TYPE_LIKE_RANKING)) {
            //点赞榜
			respone = shareService.findByLikeRankingAndPage(shareCondition);
        }
        return respone;
    }
    
    /**
	 * 根据用户名和微博内容搜索相关用户
	 * @param condition
	 * @return
	 */
	@RequestMapping("/getSearchUsers")
	@ResponseBody
	public ResponseJson getSearchUsers(String condition){
		ResponseJson result=new ResponseJson();
		try {
			JSONArray searchUsers = userService.getSearchUsers(condition);
			result.setData(searchUsers);
			result.setStatus(true);
			result.setMsg("搜素用户成功！");
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(false);
			result.setMsg("搜索用户失败！"+e.getMessage());
		}
		
		return result;
	}
}
